package www.com.springboot_20200312.rabbitmqDemo.Demo07Message.producer;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import www.com.springboot_20200312.rabbitmqDemo.Demo07Message.message.Demo07Message;

/**
 * @program: springboot_20200312
 * @ClassName Demo01Producer
 * @description:
 * @author: jht
 * @create: 2021-12-07 10:25
 * @Version 1.0
 **/
@Component
public class Demo07Producer {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void syncSend(Integer id) {
        // 创建 Demo01Message 消息
        Demo07Message message = new Demo07Message();
        message.setId(id);
        // 同步发送消息
        rabbitTemplate.convertAndSend(Demo07Message.EXCHANGE, Demo07Message.ROUTING_KEY, message);
    }

    public void syncSendDefault(Integer id) {
        // 创建 Demo01Message 消息
        Demo07Message message = new Demo07Message();
        message.setId(id);
        // 同步发送消息
        rabbitTemplate.convertAndSend(Demo07Message.QUEUE, message);
    }

    @Async
    public ListenableFuture<Void> asyncSend(Integer id) {
        try {
            // 发送消息
            this.syncSend(id);
            // 返回成功的 Future
            return AsyncResult.forValue(null);
        } catch (Throwable ex) {
            // 返回异常的 Future
            return AsyncResult.forExecutionException(ex);
        }
    }
}
